using DocumentCreationSystem.Models.Reasoning;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.IO;


namespace DocumentCreationSystem.Services.ReasoningEngine
{
    /// <summary>
    /// 推理引擎实现 - 提供完整的逻辑推理能力
    /// </summary>
    public class ReasoningEngine : IReasoningEngine
    {
        private readonly ILogger<ReasoningEngine> _logger;
        private readonly ConcurrentDictionary<string, ReasoningFact> _facts;
        private readonly ConcurrentDictionary<string, ReasoningRule> _rules;
        private readonly ReasoningStatistics _statistics;
        private readonly object _lockObject = new object();

        public ReasoningEngine(ILogger<ReasoningEngine> logger)
        {
            _logger = logger;
            _facts = new ConcurrentDictionary<string, ReasoningFact>();
            _rules = new ConcurrentDictionary<string, ReasoningRule>();
            _statistics = new ReasoningStatistics();

            _logger.LogInformation("推理引擎已初始化");
        }

        #region 事实管理

        public async Task AddFactAsync(ReasoningFact fact)
        {
            try
            {
                if (fact == null)
                    throw new ArgumentNullException(nameof(fact));

                // 检查事实是否已过期
                if (fact.IsExpired)
                {
                    _logger.LogWarning($"尝试添加已过期的事实: {fact.Id}");
                    return;
                }

                _facts.AddOrUpdate(fact.Id, fact, (key, oldValue) => fact);
                _statistics.TotalFacts = _facts.Count;

                _logger.LogDebug($"已添加事实: {fact}");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加事实失败: {fact?.Id}");
                throw;
            }
        }

        public async Task AddFactsAsync(IEnumerable<ReasoningFact> facts)
        {
            try
            {
                var factList = facts.ToList();
                var tasks = factList.Select(AddFactAsync);
                await Task.WhenAll(tasks);

                _logger.LogInformation($"批量添加了 {factList.Count} 个事实");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量添加事实失败");
                throw;
            }
        }

        public async Task<List<ReasoningFact>> QueryFactsAsync(FactQuery query)
        {
            try
            {
                var allFacts = _facts.Values.ToList();
                var filteredFacts = allFacts.Where(fact => MatchesFact(fact, query));

                // 排序
                filteredFacts = query.SortOrder switch
                {
                    FactSortOrder.ByTimestamp => filteredFacts.OrderByDescending(f => f.Timestamp),
                    FactSortOrder.ByConfidence => filteredFacts.OrderByDescending(f => f.Confidence),
                    FactSortOrder.ByWeight => filteredFacts.OrderByDescending(f => f.Weight),
                    FactSortOrder.ByRelevance => filteredFacts.OrderByDescending(f => CalculateRelevance(f, query)),
                    _ => filteredFacts.OrderByDescending(f => f.Timestamp)
                };

                var result = filteredFacts.Take(query.MaxResults).ToList();
                
                _logger.LogDebug($"查询返回 {result.Count} 个事实");
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询事实失败");
                throw;
            }
        }

        private bool MatchesFact(ReasoningFact fact, FactQuery query)
        {
            // 检查是否过期
            if (fact.IsExpired && !query.IncludeExpired)
                return false;

            // 检查主体
            if (!string.IsNullOrEmpty(query.Subject) && 
                !fact.Subject.Contains(query.Subject, StringComparison.OrdinalIgnoreCase))
                return false;

            // 检查谓词
            if (!string.IsNullOrEmpty(query.Predicate) && 
                !fact.Predicate.Contains(query.Predicate, StringComparison.OrdinalIgnoreCase))
                return false;

            // 检查客体
            if (!string.IsNullOrEmpty(query.Object) && 
                !fact.Object.Contains(query.Object, StringComparison.OrdinalIgnoreCase))
                return false;

            // 检查类型
            if (query.Type.HasValue && fact.Type != query.Type.Value)
                return false;

            // 检查置信度范围
            if (query.MinConfidence.HasValue && fact.Confidence < query.MinConfidence.Value)
                return false;

            if (query.MaxConfidence.HasValue && fact.Confidence > query.MaxConfidence.Value)
                return false;

            // 检查时间范围
            if (query.StartTime.HasValue && fact.Timestamp < query.StartTime.Value)
                return false;

            if (query.EndTime.HasValue && fact.Timestamp > query.EndTime.Value)
                return false;

            // 检查标签
            if (query.Tags.Any() && !query.Tags.Any(tag => fact.Tags.Contains(tag)))
                return false;

            return true;
        }

        private double CalculateRelevance(ReasoningFact fact, FactQuery query)
        {
            double relevance = 0.0;

            // 基于匹配程度计算相关性
            if (!string.IsNullOrEmpty(query.Subject))
                relevance += CalculateStringRelevance(fact.Subject, query.Subject);

            if (!string.IsNullOrEmpty(query.Predicate))
                relevance += CalculateStringRelevance(fact.Predicate, query.Predicate);

            if (!string.IsNullOrEmpty(query.Object))
                relevance += CalculateStringRelevance(fact.Object, query.Object);

            // 考虑置信度和权重
            relevance *= fact.Confidence * fact.Weight;

            return relevance;
        }

        private double CalculateStringRelevance(string text, string query)
        {
            if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(query))
                return 0.0;

            // 简单的字符串相似度计算
            var lowerText = text.ToLower();
            var lowerQuery = query.ToLower();

            if (lowerText == lowerQuery)
                return 1.0;

            if (lowerText.Contains(lowerQuery))
                return 0.8;

            // 计算编辑距离相似度
            var distance = CalculateLevenshteinDistance(lowerText, lowerQuery);
            var maxLength = Math.Max(lowerText.Length, lowerQuery.Length);
            return 1.0 - (double)distance / maxLength;
        }

        private int CalculateLevenshteinDistance(string s1, string s2)
        {
            var matrix = new int[s1.Length + 1, s2.Length + 1];

            for (int i = 0; i <= s1.Length; i++)
                matrix[i, 0] = i;

            for (int j = 0; j <= s2.Length; j++)
                matrix[0, j] = j;

            for (int i = 1; i <= s1.Length; i++)
            {
                for (int j = 1; j <= s2.Length; j++)
                {
                    var cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
                    matrix[i, j] = Math.Min(
                        Math.Min(matrix[i - 1, j] + 1, matrix[i, j - 1] + 1),
                        matrix[i - 1, j - 1] + cost);
                }
            }

            return matrix[s1.Length, s2.Length];
        }

        #endregion

        #region 规则管理

        public async Task AddRuleAsync(ReasoningRule rule)
        {
            try
            {
                if (rule == null)
                    throw new ArgumentNullException(nameof(rule));

                _rules.AddOrUpdate(rule.Id, rule, (key, oldValue) => rule);
                _statistics.TotalRules = _rules.Count;

                _logger.LogDebug($"已添加规则: {rule.Name}");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加规则失败: {rule?.Id}");
                throw;
            }
        }

        public async Task AddRulesAsync(IEnumerable<ReasoningRule> rules)
        {
            try
            {
                var ruleList = rules.ToList();
                var tasks = ruleList.Select(AddRuleAsync);
                await Task.WhenAll(tasks);

                _logger.LogInformation($"批量添加了 {ruleList.Count} 个规则");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量添加规则失败");
                throw;
            }
        }

        #endregion

        #region 推理执行

        public async Task<ReasoningResult> ReasonAsync(ReasoningQuery query)
        {
            var stopwatch = Stopwatch.StartNew();
            var result = new ReasoningResult
            {
                QueryId = query.Id,
                Timestamp = DateTime.Now
            };

            try
            {
                _statistics.TotalQueries++;

                _logger.LogInformation($"开始推理查询: {query.Id}, 类型: {query.Type}");

                switch (query.Type)
                {
                    case ReasoningType.Forward:
                        result = await PerformForwardReasoningAsync(query);
                        break;
                    case ReasoningType.Backward:
                        result = await PerformBackwardReasoningAsync(query);
                        break;
                    case ReasoningType.Bidirectional:
                        result = await PerformBidirectionalReasoningAsync(query);
                        break;
                    default:
                        throw new NotSupportedException($"不支持的推理类型: {query.Type}");
                }

                result.IsSuccess = true;
                _statistics.SuccessfulReasoning++;
                
                stopwatch.Stop();
                result.ReasoningTimeMs = stopwatch.ElapsedMilliseconds;

                // 更新统计信息
                UpdateReasoningStatistics(result);

                _logger.LogInformation($"推理完成: {query.Id}, 耗时: {result.ReasoningTimeMs}ms, 推导事实: {result.DerivedFacts.Count}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"推理失败: {query.Id}");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                _statistics.FailedReasoning++;
                
                stopwatch.Stop();
                result.ReasoningTimeMs = stopwatch.ElapsedMilliseconds;
            }

            return result;
        }

        private async Task<ReasoningResult> PerformForwardReasoningAsync(ReasoningQuery query)
        {
            var result = new ReasoningResult { QueryId = query.Id };
            var reasoningChain = new ReasoningChain { Goal = query.Goal };
            var derivedFacts = new List<ReasoningFact>();
            var usedRules = new HashSet<string>();

            // 获取初始事实
            var currentFacts = _facts.Values.Where(f => !f.IsExpired).ToList();
            reasoningChain.InitialFacts = currentFacts.ToList();

            for (int depth = 0; depth < query.MaxDepth; depth++)
            {
                var newFacts = new List<ReasoningFact>();
                var stepNumber = depth + 1;

                foreach (var rule in _rules.Values.Where(r => r.IsEnabled))
                {
                    var matchResult = await TryApplyRuleAsync(rule, currentFacts, query.Context);
                    if (matchResult.Success)
                    {
                        var step = new ReasoningStep
                        {
                            StepNumber = stepNumber,
                            Rule = rule,
                            InputFacts = matchResult.MatchedFacts,
                            OutputFacts = matchResult.DerivedFacts,
                            Type = Models.Reasoning.StepType.RuleApplication,
                            Confidence = matchResult.Confidence,
                            Description = $"应用规则: {rule.Name}",
                            ExecutedAt = DateTime.Now
                        };

                        reasoningChain.Steps.Add(step);
                        newFacts.AddRange(matchResult.DerivedFacts);
                        usedRules.Add(rule.Id);

                        // 更新规则使用统计
                        rule.UsageCount++;
                        rule.LastUsedAt = DateTime.Now;
                    }
                }

                if (!newFacts.Any())
                    break; // 没有新的推导，停止推理

                // 过滤低置信度的事实
                var validFacts = newFacts.Where(f => f.Confidence >= query.MinConfidence).ToList();
                derivedFacts.AddRange(validFacts);
                currentFacts.AddRange(validFacts);

                // 检查是否达到目标
                if (IsGoalReached(query.Goal, validFacts))
                {
                    reasoningChain.IsComplete = true;
                    break;
                }
            }

            result.DerivedFacts = derivedFacts;
            result.RulesUsed = usedRules.Count;
            result.Confidence = CalculateOverallConfidence(derivedFacts);

            if (query.IncludeReasoningChain)
            {
                reasoningChain.Confidence = result.Confidence;
                result.ReasoningChain = reasoningChain;
            }

            return result;
        }

        private async Task<ReasoningResult> PerformBackwardReasoningAsync(ReasoningQuery query)
        {
            // 后向推理实现
            var result = new ReasoningResult { QueryId = query.Id };
            var reasoningChain = await BackwardReasoningAsync(query.Goal);
            
            result.ReasoningChain = reasoningChain;
            result.DerivedFacts = ExtractFactsFromChain(reasoningChain);
            result.Confidence = reasoningChain.Confidence;
            result.RulesUsed = reasoningChain.Steps.Count;

            return result;
        }

        private async Task<ReasoningResult> PerformBidirectionalReasoningAsync(ReasoningQuery query)
        {
            // 双向推理：结合前向和后向推理
            var forwardTask = PerformForwardReasoningAsync(query);
            var backwardTask = PerformBackwardReasoningAsync(query);

            var results = await Task.WhenAll(forwardTask, backwardTask);
            var forwardResult = results[0];
            var backwardResult = results[1];

            // 合并结果
            var combinedResult = new ReasoningResult
            {
                QueryId = query.Id,
                IsSuccess = forwardResult.IsSuccess || backwardResult.IsSuccess,
                DerivedFacts = forwardResult.DerivedFacts.Union(backwardResult.DerivedFacts).ToList(),
                Confidence = Math.Max(forwardResult.Confidence, backwardResult.Confidence),
                RulesUsed = forwardResult.RulesUsed + backwardResult.RulesUsed
            };

            return combinedResult;
        }

        #endregion

        #region 辅助方法

        private async Task<RuleMatchResult> TryApplyRuleAsync(ReasoningRule rule, List<ReasoningFact> facts, Dictionary<string, object> context)
        {
            var result = new RuleMatchResult();

            try
            {
                // 检查规则条件
                var matchedFacts = new List<ReasoningFact>();
                var conditionsMet = true;

                foreach (var condition in rule.Conditions)
                {
                    var matchingFacts = facts.Where(f => MatchesCondition(f, condition)).ToList();
                    if (!matchingFacts.Any())
                    {
                        conditionsMet = false;
                        break;
                    }
                    matchedFacts.AddRange(matchingFacts);
                }

                if (conditionsMet)
                {
                    // 应用规则结论
                    var derivedFacts = new List<ReasoningFact>();
                    foreach (var conclusion in rule.Conclusions)
                    {
                        if (conclusion.Type == ConclusionType.AddFact && conclusion.NewFact != null)
                        {
                            var newFact = CloneFact(conclusion.NewFact);
                            newFact.Confidence = conclusion.Confidence * rule.Confidence;
                            newFact.Source = $"Rule:{rule.Id}";
                            newFact.Type = FactType.Derived;
                            derivedFacts.Add(newFact);
                        }
                    }

                    result.Success = true;
                    result.MatchedFacts = matchedFacts.Distinct().ToList();
                    result.DerivedFacts = derivedFacts;
                    result.Confidence = rule.Confidence;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"应用规则失败: {rule.Id}");
            }

            return await Task.FromResult(result);
        }

        private bool MatchesCondition(ReasoningFact fact, RuleCondition condition)
        {
            switch (condition.Type)
            {
                case ConditionType.FactMatch:
                    return MatchesFactPattern(fact, condition.Pattern);
                case ConditionType.NumericComparison:
                    return PerformNumericComparison(fact, condition);
                case ConditionType.StringMatch:
                    return PerformStringMatch(fact, condition);
                default:
                    return false;
            }
        }

        private bool MatchesFactPattern(ReasoningFact fact, FactPattern pattern)
        {
            var options = pattern.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;

            if (!string.IsNullOrEmpty(pattern.SubjectPattern))
            {
                if (pattern.UseRegex)
                {
                    if (!Regex.IsMatch(fact.Subject, pattern.SubjectPattern, 
                        pattern.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                        return false;
                }
                else
                {
                    if (!fact.Subject.Contains(pattern.SubjectPattern, options))
                        return false;
                }
            }

            if (!string.IsNullOrEmpty(pattern.PredicatePattern))
            {
                if (pattern.UseRegex)
                {
                    if (!Regex.IsMatch(fact.Predicate, pattern.PredicatePattern,
                        pattern.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                        return false;
                }
                else
                {
                    if (!fact.Predicate.Contains(pattern.PredicatePattern, options))
                        return false;
                }
            }

            if (!string.IsNullOrEmpty(pattern.ObjectPattern))
            {
                if (pattern.UseRegex)
                {
                    if (!Regex.IsMatch(fact.Object, pattern.ObjectPattern,
                        pattern.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                        return false;
                }
                else
                {
                    if (!fact.Object.Contains(pattern.ObjectPattern, options))
                        return false;
                }
            }

            return true;
        }

        private bool PerformNumericComparison(ReasoningFact fact, RuleCondition condition)
        {
            // 实现数值比较逻辑
            return false; // 简化实现
        }

        private bool PerformStringMatch(ReasoningFact fact, RuleCondition condition)
        {
            // 实现字符串匹配逻辑
            return false; // 简化实现
        }

        private bool IsGoalReached(ReasoningFact goal, List<ReasoningFact> facts)
        {
            return facts.Any(f => 
                f.Subject.Equals(goal.Subject, StringComparison.OrdinalIgnoreCase) &&
                f.Predicate.Equals(goal.Predicate, StringComparison.OrdinalIgnoreCase) &&
                f.Object.Equals(goal.Object, StringComparison.OrdinalIgnoreCase));
        }

        private double CalculateOverallConfidence(List<ReasoningFact> facts)
        {
            if (!facts.Any())
                return 0.0;

            return facts.Average(f => f.Confidence);
        }

        private ReasoningFact CloneFact(ReasoningFact original)
        {
            return new ReasoningFact
            {
                Id = Guid.NewGuid().ToString(),
                Subject = original.Subject,
                Predicate = original.Predicate,
                Object = original.Object,
                Confidence = original.Confidence,
                Type = original.Type,
                Source = original.Source,
                Tags = new List<string>(original.Tags),
                Context = new Dictionary<string, object>(original.Context),
                Weight = original.Weight,
                IsTemporary = original.IsTemporary,
                ExpiryTime = original.ExpiryTime
            };
        }

        private List<ReasoningFact> ExtractFactsFromChain(ReasoningChain chain)
        {
            var facts = new List<ReasoningFact>();
            foreach (var step in chain.Steps)
            {
                facts.AddRange(step.OutputFacts);
            }
            return facts.Distinct().ToList();
        }

        private void UpdateReasoningStatistics(ReasoningResult result)
        {
            lock (_lockObject)
            {
                var totalTime = _statistics.AverageReasoningTimeMs * (_statistics.SuccessfulReasoning - 1) + result.ReasoningTimeMs;
                _statistics.AverageReasoningTimeMs = totalTime / _statistics.SuccessfulReasoning;

                if (result.ReasoningTimeMs > _statistics.MaxReasoningTimeMs)
                    _statistics.MaxReasoningTimeMs = result.ReasoningTimeMs;

                if (result.ReasoningTimeMs < _statistics.MinReasoningTimeMs)
                    _statistics.MinReasoningTimeMs = result.ReasoningTimeMs;

                if (result.ReasoningChain != null)
                {
                    var chainLength = result.ReasoningChain.Length;
                    var totalChainLength = _statistics.AverageChainLength * (_statistics.SuccessfulReasoning - 1) + chainLength;
                    _statistics.AverageChainLength = totalChainLength / _statistics.SuccessfulReasoning;

                    if (chainLength > _statistics.MaxChainLength)
                        _statistics.MaxChainLength = chainLength;
                }
            }
        }

        #endregion

        #region 接口实现的其他方法

        public async Task<List<ReasoningFact>> ForwardReasoningAsync(List<ReasoningFact> initialFacts)
        {
            var query = new ReasoningQuery
            {
                Type = ReasoningType.Forward,
                Goal = new ReasoningFact() // 空目标，进行开放式推理
            };

            // 临时添加初始事实
            var originalFactIds = new List<string>();
            foreach (var fact in initialFacts)
            {
                if (!_facts.ContainsKey(fact.Id))
                {
                    await AddFactAsync(fact);
                    originalFactIds.Add(fact.Id);
                }
            }

            try
            {
                var result = await ReasonAsync(query);
                return result.DerivedFacts;
            }
            finally
            {
                // 清理临时添加的事实
                foreach (var factId in originalFactIds)
                {
                    await RemoveFactAsync(factId);
                }
            }
        }

        public async Task<ReasoningChain> BackwardReasoningAsync(ReasoningFact goal)
        {
            var chain = new ReasoningChain { Goal = goal };
            var visited = new HashSet<string>();

            await BuildBackwardChainAsync(goal, chain, visited, 0, 10);
            return chain;
        }

        private async Task<bool> BuildBackwardChainAsync(ReasoningFact goal, ReasoningChain chain, HashSet<string> visited, int depth, int maxDepth)
        {
            if (depth >= maxDepth || visited.Contains(goal.ToString()))
                return false;

            visited.Add(goal.ToString());

            // 查找能推导出目标的规则
            foreach (var rule in _rules.Values.Where(r => r.IsEnabled))
            {
                foreach (var conclusion in rule.Conclusions)
                {
                    if (conclusion.Type == ConclusionType.AddFact && 
                        conclusion.NewFact != null &&
                        FactsMatch(conclusion.NewFact, goal))
                    {
                        var step = new ReasoningStep
                        {
                            StepNumber = chain.Steps.Count + 1,
                            Rule = rule,
                            OutputFacts = new List<ReasoningFact> { goal },
                            Type = Models.Reasoning.StepType.RuleApplication,
                            Confidence = rule.Confidence,
                            Description = $"后向应用规则: {rule.Name}"
                        };

                        // 递归查找前提条件
                        var allPremisesSatisfied = true;
                        foreach (var condition in rule.Conditions)
                        {
                            var premise = CreateFactFromCondition(condition);
                            if (premise != null)
                            {
                                step.InputFacts.Add(premise);
                                if (!await BuildBackwardChainAsync(premise, chain, visited, depth + 1, maxDepth))
                                {
                                    allPremisesSatisfied = false;
                                }
                            }
                        }

                        if (allPremisesSatisfied)
                        {
                            chain.Steps.Insert(0, step); // 插入到链的开始
                            chain.IsComplete = true;
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        private bool FactsMatch(ReasoningFact fact1, ReasoningFact fact2)
        {
            return fact1.Subject.Equals(fact2.Subject, StringComparison.OrdinalIgnoreCase) &&
                   fact1.Predicate.Equals(fact2.Predicate, StringComparison.OrdinalIgnoreCase) &&
                   fact1.Object.Equals(fact2.Object, StringComparison.OrdinalIgnoreCase);
        }

        private ReasoningFact? CreateFactFromCondition(RuleCondition condition)
        {
            if (condition.Type == ConditionType.FactMatch && condition.Pattern != null)
            {
                return new ReasoningFact
                {
                    Subject = condition.Pattern.SubjectPattern ?? "",
                    Predicate = condition.Pattern.PredicatePattern ?? "",
                    Object = condition.Pattern.ObjectPattern ?? "",
                    Type = FactType.Hypothesis
                };
            }
            return null;
        }

        public async Task<ConsistencyCheckResult> CheckConsistencyAsync(List<ReasoningFact> facts)
        {
            var result = new ConsistencyCheckResult
            {
                FactsChecked = facts.Count,
                CheckedAt = DateTime.Now
            };

            var stopwatch = Stopwatch.StartNew();

            try
            {
                var conflicts = new List<FactConflict>();

                // 检查直接矛盾
                for (int i = 0; i < facts.Count; i++)
                {
                    for (int j = i + 1; j < facts.Count; j++)
                    {
                        var conflict = DetectConflict(facts[i], facts[j]);
                        if (conflict != null)
                        {
                            conflicts.Add(conflict);
                        }
                    }
                }

                result.Conflicts = conflicts;
                result.IsConsistent = !conflicts.Any();
                result.ConsistencyScore = conflicts.Any() ? 
                    Math.Max(0.0, 1.0 - (double)conflicts.Count / facts.Count) : 1.0;

                stopwatch.Stop();
                result.CheckTimeMs = stopwatch.ElapsedMilliseconds;

                _logger.LogInformation($"一致性检查完成: {facts.Count} 个事实, {conflicts.Count} 个冲突, 耗时: {result.CheckTimeMs}ms");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "一致性检查失败");
                result.IsConsistent = false;
                stopwatch.Stop();
                result.CheckTimeMs = stopwatch.ElapsedMilliseconds;
            }

            return result;
        }

        private FactConflict? DetectConflict(ReasoningFact fact1, ReasoningFact fact2)
        {
            // 检查直接矛盾：相同主体和谓词，但不同客体
            if (fact1.Subject.Equals(fact2.Subject, StringComparison.OrdinalIgnoreCase) &&
                fact1.Predicate.Equals(fact2.Predicate, StringComparison.OrdinalIgnoreCase) &&
                !fact1.Object.Equals(fact2.Object, StringComparison.OrdinalIgnoreCase))
            {
                // 检查是否为互斥关系
                if (AreObjectsContradictory(fact1.Object, fact2.Object))
                {
                    return new FactConflict
                    {
                        ConflictingFacts = new List<ReasoningFact> { fact1, fact2 },
                        Type = ConflictType.Contradiction,
                        Description = $"矛盾: {fact1.Subject} 不能同时 {fact1.Predicate} {fact1.Object} 和 {fact2.Object}",
                        Severity = 1.0
                    };
                }
            }

            return null;
        }

        private bool AreObjectsContradictory(string object1, string object2)
        {
            // 简单的矛盾检测逻辑
            var contradictoryPairs = new Dictionary<string, string[]>
            {
                { "true", new[] { "false" } },
                { "yes", new[] { "no" } },
                { "alive", new[] { "dead" } },
                { "present", new[] { "absent" } },
                { "hot", new[] { "cold" } },
                { "big", new[] { "small" } },
                { "good", new[] { "bad" } }
            };

            var obj1Lower = object1.ToLower();
            var obj2Lower = object2.ToLower();

            foreach (var pair in contradictoryPairs)
            {
                if ((obj1Lower == pair.Key && pair.Value.Contains(obj2Lower)) ||
                    (obj2Lower == pair.Key && pair.Value.Contains(obj1Lower)))
                {
                    return true;
                }
            }

            return false;
        }

        public async Task<ReasoningExplanation> ExplainReasoningAsync(ReasoningResult result)
        {
            var explanation = new ReasoningExplanation
            {
                ReasoningResultId = result.Id,
                Level = ExplanationLevel.Medium,
                GeneratedAt = DateTime.Now
            };

            try
            {
                // 生成自然语言解释
                var explanationText = $"推理过程分析：\n";
                explanationText += $"- 推理成功: {(result.IsSuccess ? "是" : "否")}\n";
                explanationText += $"- 推导出 {result.DerivedFacts.Count} 个新事实\n";
                explanationText += $"- 使用了 {result.RulesUsed} 个规则\n";
                explanationText += $"- 总体置信度: {result.Confidence:F2}\n";
                explanationText += $"- 推理时间: {result.ReasoningTimeMs}ms\n";

                if (result.ReasoningChain != null)
                {
                    explanationText += $"- 推理链长度: {result.ReasoningChain.Length} 步\n\n";
                    explanationText += "推理步骤详情：\n";

                    var stepExplanations = new List<StepExplanation>();
                    foreach (var step in result.ReasoningChain.Steps)
                    {
                        var stepExplanation = new StepExplanation
                        {
                            StepId = step.Id,
                            Explanation = $"步骤 {step.StepNumber}: {step.Description}",
                            RuleExplanation = step.Rule?.Description,
                            RuleSelectionReason = $"规则置信度: {step.Rule?.Confidence:F2}, 匹配度高"
                        };
                        stepExplanations.Add(stepExplanation);

                        explanationText += $"  {stepExplanation.Explanation}\n";
                        if (!string.IsNullOrEmpty(stepExplanation.RuleExplanation))
                        {
                            explanationText += $"    规则说明: {stepExplanation.RuleExplanation}\n";
                        }
                    }

                    explanation.StepExplanations = stepExplanations;
                }

                explanation.NaturalLanguageExplanation = explanationText;

                _logger.LogDebug($"生成推理解释: {result.Id}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成推理解释失败: {result.Id}");
                explanation.NaturalLanguageExplanation = "解释生成失败: " + ex.Message;
            }

            return explanation;
        }

        public async Task<ReasoningStatistics> GetStatisticsAsync()
        {
            _statistics.GeneratedAt = DateTime.Now;
            return await Task.FromResult(_statistics);
        }

        public async Task ClearKnowledgeBaseAsync()
        {
            _facts.Clear();
            _rules.Clear();
            _statistics.TotalFacts = 0;
            _statistics.TotalRules = 0;
            
            _logger.LogInformation("知识库已清空");
            await Task.CompletedTask;
        }

        public async Task SaveKnowledgeBaseAsync(string filePath)
        {
            try
            {
                var knowledgeBase = new
                {
                    Facts = _facts.Values.ToList(),
                    Rules = _rules.Values.ToList(),
                    Statistics = _statistics,
                    SavedAt = DateTime.Now
                };

                var json = JsonSerializer.Serialize(knowledgeBase, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                await File.WriteAllTextAsync(filePath, json);
                _logger.LogInformation($"知识库已保存到: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存知识库失败: {filePath}");
                throw;
            }
        }

        public async Task LoadKnowledgeBaseAsync(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    throw new FileNotFoundException($"知识库文件不存在: {filePath}");

                var json = await File.ReadAllTextAsync(filePath);
                var knowledgeBase = JsonSerializer.Deserialize<dynamic>(json);

                // 这里需要更复杂的反序列化逻辑
                // 简化实现
                await ClearKnowledgeBaseAsync();
                
                _logger.LogInformation($"知识库已从文件加载: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载知识库失败: {filePath}");
                throw;
            }
        }

        public async Task<List<ReasoningFact>> GetAllFactsAsync()
        {
            return await Task.FromResult(_facts.Values.ToList());
        }

        public async Task<List<ReasoningRule>> GetAllRulesAsync()
        {
            return await Task.FromResult(_rules.Values.ToList());
        }

        public async Task RemoveFactAsync(string factId)
        {
            if (_facts.TryRemove(factId, out var removedFact))
            {
                _statistics.TotalFacts = _facts.Count;
                _logger.LogDebug($"已删除事实: {factId}");
            }
            await Task.CompletedTask;
        }

        public async Task RemoveRuleAsync(string ruleId)
        {
            if (_rules.TryRemove(ruleId, out var removedRule))
            {
                _statistics.TotalRules = _rules.Count;
                _logger.LogDebug($"已删除规则: {ruleId}");
            }
            await Task.CompletedTask;
        }

        public async Task UpdateFactAsync(ReasoningFact fact)
        {
            if (_facts.ContainsKey(fact.Id))
            {
                _facts[fact.Id] = fact;
                _logger.LogDebug($"已更新事实: {fact.Id}");
            }
            await Task.CompletedTask;
        }

        public async Task UpdateRuleAsync(ReasoningRule rule)
        {
            if (_rules.ContainsKey(rule.Id))
            {
                _rules[rule.Id] = rule;
                _logger.LogDebug($"已更新规则: {rule.Id}");
            }
            await Task.CompletedTask;
        }

        public async Task<List<ReasoningFact>> SearchFactsAsync(string searchTerm, int maxResults = 10)
        {
            var query = new FactQuery
            {
                Subject = searchTerm,
                Predicate = searchTerm,
                Object = searchTerm,
                MaxResults = maxResults,
                SortOrder = FactSortOrder.ByRelevance
            };

            // 使用OR逻辑搜索
            var allFacts = _facts.Values.ToList();
            var matchingFacts = allFacts.Where(fact =>
                fact.Subject.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                fact.Predicate.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                fact.Object.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                fact.Tags.Any(tag => tag.Contains(searchTerm, StringComparison.OrdinalIgnoreCase))
            ).Take(maxResults).ToList();

            return await Task.FromResult(matchingFacts);
        }

        public async Task<FactDependencyGraph> GetFactDependenciesAsync(string factId)
        {
            var graph = new FactDependencyGraph { RootFactId = factId };
            
            if (_facts.TryGetValue(factId, out var rootFact))
            {
                var visited = new HashSet<string>();
                await BuildDependencyGraphAsync(rootFact, graph, visited, 0, 5);
            }

            return graph;
        }

        private async Task BuildDependencyGraphAsync(ReasoningFact fact, FactDependencyGraph graph, HashSet<string> visited, int level, int maxLevel)
        {
            if (level >= maxLevel || visited.Contains(fact.Id))
                return;

            visited.Add(fact.Id);

            var node = new DependencyNode
            {
                Fact = fact,
                Level = level,
                Type = fact.Type == FactType.Derived ? NodeType.Derived : NodeType.Fact
            };

            graph.Nodes.Add(node);

            // 查找依赖关系（简化实现）
            // 在实际实现中，需要跟踪事实的推导历史
            
            await Task.CompletedTask;
        }

        // 概率推理、类比推理、因果推理的简化实现
        public async Task<ProbabilisticReasoningResult> ProbabilisticReasoningAsync(ProbabilisticQuery query)
        {
            // 简化的概率推理实现
            var result = new ProbabilisticReasoningResult
            {
                QueryId = query.Id,
                Probability = 0.5, // 简化实现
                HasConverged = true,
                Iterations = 1
            };

            return await Task.FromResult(result);
        }

        public async Task<AnalogyReasoningResult> AnalogyReasoningAsync(ReasoningCase sourceCase, ReasoningCase targetCase)
        {
            // 简化的类比推理实现
            var result = new AnalogyReasoningResult
            {
                SourceCaseId = sourceCase.Id,
                TargetCaseId = targetCase.Id,
                SimilarityScore = 0.5, // 简化实现
                PredictionConfidence = 0.5
            };

            return await Task.FromResult(result);
        }

        public async Task<CausalReasoningResult> CausalReasoningAsync(ReasoningFact cause, ReasoningFact effect)
        {
            // 简化的因果推理实现
            var result = new CausalReasoningResult
            {
                CauseFactId = cause.Id,
                EffectFactId = effect.Id,
                CausalStrength = 0.5, // 简化实现
                Type = CausalType.Direct
            };

            return await Task.FromResult(result);
        }

        #endregion
    }

    /// <summary>
    /// 规则匹配结果
    /// </summary>
    internal class RuleMatchResult
    {
        public bool Success { get; set; } = false;
        public List<ReasoningFact> MatchedFacts { get; set; } = new();
        public List<ReasoningFact> DerivedFacts { get; set; } = new();
        public double Confidence { get; set; } = 1.0;
    }
}
